import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import { Card, Button, message, Tooltip, Icon, Row, Col, Progress, Modal, List, DatePicker } from 'antd';

import TrimSpan from '../../components/TrimSpan';
import { taskTaobaoStatus, taskTaobaoSummary, queryNeedSyncTasks } from '../../services/task';

const { RangePicker } = DatePicker;

@connect(state => ({
  currentUser: state.user.currentUser,
  visible: state.statistics.syncModal.visible,
  wetaoUser: state.user.wetaoUser,
}))

export default class SyncTaobaoDataModal extends PureComponent {
  state = {
    nicaiCrx: null,
    version: '',
    percent: 0,
    list: [],
    pagination: {
      total: 0,
      pageSize: 1,
      current: 1,
    },
    syncing: false,
    taobaoData: [],
    publish_taobao_time_start: null,
    publish_taobao_time_end: null,
  }
  componentWillReceiveProps(nextProps) {
    if (!this.props.visible && nextProps.visible) {
      const nicaiCrx = document.getElementById('nicaiCrx');
      nicaiCrx.addEventListener('setVersion', this.setVersion);
      nicaiCrx.addEventListener('setFeedback', this.setFeedback);
      nicaiCrx.addEventListener('setAnalyzeData', this.setAnalyzeData);
      if (!this.state.nicaiCrx) {
        this.setState({ nicaiCrx }, () => {
          this.handleGetVersion();
        });
      } else {
        this.handleGetVersion();
      }
      const publish_taobao_time_start = new Date();
      publish_taobao_time_start.setDate(publish_taobao_time_start.getDate() - 7);
      publish_taobao_time_start.setHours(0, 0, 0, 0);
      const publish_taobao_time_end = new Date();
      this.setState({
        percent: 0,
        list: [],
        pagination: {
          total: 0,
          pageSize: 1,
          current: 1,
        },
        syncing: false,
        taobaoData: [],
        publish_taobao_time_start,
        publish_taobao_time_end
      });
    } else if (this.props.visible && !nextProps.visible) {
      const nicaiCrx = document.getElementById('nicaiCrx');
      nicaiCrx.removeEventListener('setAnalyzeData', this.setAnalyzeData);
      nicaiCrx.removeEventListener('setFeedback', this.setFeedback);
      nicaiCrx.removeEventListener('setVersion', this.setVersion);
    }
  }
  handleGetWetaoUser = () => {
    const nicaiCrx = document.getElementById('nicaiCrx');
    const data = {
      url: 'https://we.taobao.com/account/getAccountSettingInfo.json?__version__=3.0',
      type: 'GET',
      actionName: 'setWetaoUser'
    };
    nicaiCrx.innerText = JSON.stringify(data);
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('taobaoRequest', true, true);
    nicaiCrx.dispatchEvent(customEvent);
  }
  setVersion = (e) => {
    const data = JSON.parse(e.target.innerText);
    if (data.version) {
      this.setState({
        version: data.version,
      });
      this.handleGetWetaoUser();
    }
    if (data.error) {
      message.destroy();
      message.warn(data.msg, 60 * 60);
    }
  }
  setFeedback = (e) => {
    const data = JSON.parse(e.target.innerText);
    if (data.result && data.result.status === 'SUCCESS') {
      // console.log(data.result);
      let content = null;
      if (data.task.formData.activityId !== undefined) {
        if (data.result.data.itemList && data.result.data.itemList.length === 1) {
          content = data.result.data.itemList[0];
        } else {
          content = data.result.data.itemList.find(item => String(item.id) === data.task.taobao.contentId);
        }
      } else {
        const ContentTable = data.result.data.components.find(item => item.component === 'ContentTable');
        if (ContentTable && ContentTable.props.dataSource.length === 1) {
          content = ContentTable.props.dataSource[0];
        } else {
          content = ContentTable.props.dataSource.find(item => String(item.id) === data.task.taobao.contentId);
        }
      }
      
      // console.log(content);
      let backgroundColor = 'none';
      let msg = '同步正常';
      let iconColor = 'green';
      if (content) {
        const { currentUser } = this.props;
        taskTaobaoStatus({
          user_id: currentUser._id,
          _id: data.task._id,
          taobao: content,
        });
        backgroundColor = '#f6ffed';
      } else {
        msg = '未找到';
        backgroundColor = '#fff1f0';
        iconColor = 'red';
      }
      const taobaoData = [...this.state.taobaoData];
      
      taobaoData.unshift({ task: data.task, iconColor, msg, backgroundColor });
      const { pagination } = this.state;
      if (pagination.total > 0)
      this.setState({ percent: Math.ceil( taobaoData.length / pagination.total * 100), taobaoData });
      if (taobaoData.length < pagination.total) {
        this.handleGetNeedSyncTasks(this.state.pagination.current + 1);
      } else {
        message.success('同步完了');
        this.setState({
          syncing: false
        });
      }
    } else if (data.result && data.result.status === 'NOT_LOGIN') {
      message.destroy();
      message.error(`淘宝：${data.result.message}`);
      this.setState({
        syncing: false
      });
    }
  }
  setAnalyzeData = (e) => {
    const data = JSON.parse(e.target.innerText);
    const { currentUser } = this.props;
    if (data.summary) {
      taskTaobaoSummary({
        user_id: currentUser._id,
        _id: data.task._id,
        summary: data.summary,
      });
    }
  }
  handleGetVersion = () => {
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('getVersion', true, true);
    this.state.nicaiCrx.dispatchEvent(customEvent);
  }
  handleGetFeedback = () => {
    const { version } = this.state;
    if (version && version.length > 0) {
      const arr = version.split('.');
      const versionNumber = Number(arr[0]) * 100 + Number(arr[1]) * 10 + Number(arr[2]);
      if (versionNumber < 128) { // 1.0.4
        message.destroy();
        message.warn('请更新插件，并重启浏览器！');
      } else {
        this.setState({
          percent: 0,
          list: [],
          pagination: {
            total: 0,
            pageSize: 1,
            current: 1,
          },
          syncing: true,
          taobaoData: [],
        });
        this.handleGetNeedSyncTasks(1);
      }
    } else {
      message.destroy();
      message.warn('请安装尼采创作平台插件！', 60 * 60);
    }
  }
  handleGetNeedSyncTasks = (currentPage) => {
    const { currentUser } = this.props
    queryNeedSyncTasks({
      user_id: currentUser._id,
      publish_taobao_time_start: moment(this.state.publish_taobao_time_start).toDate(),
      publish_taobao_time_end: moment(this.state.publish_taobao_time_end).toDate(),
      currentPage,
      pageSize: this.state.pagination.pageSize,
    }).then((result) => {
      if (result.error) {
        message.error(result.msg);
      } else {
        if (result.list.length === 0) {
          message.warn('没有需要同步的数据');
          this.setState({
            syncing: false
          });
        } else {
          this.setState({
            list: result.list,
            pagination: result.pagination,
          });
          this.state.nicaiCrx.innerText = JSON.stringify({ user_id: currentUser._id, task: result.list[0] });
          const customEvent = document.createEvent('Event');
          customEvent.initEvent('getFeedback', true, true);
          this.state.nicaiCrx.dispatchEvent(customEvent);
        }
      }
    });
  }
  handleCancel = () => {
    this.props.dispatch({
      type: 'statistics/toggleSyncModal',
      payload: { visible: false },
    });
  }
  handleTimeRangeChange = (value) => {
    this.setState({
      publish_taobao_time_start: value[0].toDate(),
      publish_taobao_time_end: value[1].toDate(),
    });
  }
  render() {
    const { visible, wetaoUser } = this.props;
    let title = '数据同步';
    if (this.state.syncing) title = '请勿离开';
    if (wetaoUser.type) {
      title = `${title} （${wetaoUser.type ? wetaoUser.type : ''}`;
      title = `${title} ${wetaoUser.name ? wetaoUser.name : ''}）`;
    }
    return (
      <Modal
      visible={visible}
      title={title}
      width="960px"
      footer={null}
      onCancel={this.handleCancel}
      maskClosable={false}
      >
        <Row>
          <Col span={12}>
            <Progress type="circle" percent={this.state.percent} format={percent => `${percent} %`} width={360}/>
          </Col>
          <Col span={12}>
            <div id="taobaoDataList" style={{ height: 360, overflow: 'auto' }}>
              <List
                style={{ minHeight: 360 }}
                size="small"
                // header={<div><span style={{ marginRight: 80 }}>内容ID</span><span>内容标题</span></div>}
                header={null}
                footer={null}
                bordered
                dataSource={this.state.taobaoData}
                renderItem={item => (
                  <List.Item style={{ background: item.backgroundColor }}>
                    <span>
                      <TrimSpan text={item.task.title || item.task.name} length={20}/>
                      <span style={{ marginLeft: 10 }}>{item.task.channel_name}</span>
                      <span style={{ marginLeft: 10 }}>
                        <Icon
                        type={item.iconColor === 'green' ? 'check-circle' : 'close-circle' }
                        style={{ color: item.iconColor, marginRight: 5 }}/>
                        {item.msg}
                      </span>
                    </span>
                  </List.Item>)}
              />
            </div>
          </Col>
        </Row>
        <Row style={{ marginTop: 20 }}>
          <Col span={12}>
          </Col>
          <Col span={8}>
            <RangePicker allowClear={false} style={{ width: 240 }}
              value={[moment(this.state.publish_taobao_time_start), moment(this.state.publish_taobao_time_end)]}
              onChange={this.handleTimeRangeChange}
            />
            <Tooltip placement="top" title="发布到淘宝的时间">
              <Icon type="question-circle-o" style={{ marginLeft: 5 }} />
            </Tooltip>
          </Col>
          <Col span={4}>
            <Button disabled={this.state.syncing || !this.state.version} type="primary" onClick={this.handleGetFeedback}>
              开始同步
            </Button>
          </Col>
        </Row>
      </Modal>
    );
  }
}
